package com.han.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JsonUtils {

    //private static ObjectMapper mapper = new ObjectMapper();

	public static String getObjectStr(String jsonString, String key) {

		String[] keys = key.split("\\.");
		JSONObject object = (JSONObject) JSON.parse(jsonString);
		for (int i = 0; i < keys.length; i++) {

			String keyPart = keys[i];
			if (i != keys.length - 1) {
				// 首先判断是否传入数组下标
				if (keyPart.indexOf("[") >= 0) {
					// 拿到下标
					int index = Integer.parseInt(keyPart.substring(
							keyPart.indexOf("[") + 1, keyPart.indexOf("]")));
					JSONArray jsonArray = object.getJSONArray(keyPart
							.substring(0, keyPart.indexOf("[")));
					object = jsonArray.getJSONObject(index);
				} else {
					object = object.getJSONObject(keyPart);
				}
			}
		}
		// 首先判断是否传入数组下标
		if (keys[keys.length - 1].indexOf("[") >= 0) {
			// 拿到下标
			int index = Integer.parseInt(keys[keys.length - 1].substring(
					keys[keys.length - 1].indexOf("[") + 1,
					keys[keys.length - 1].indexOf("]")));
			JSONArray jsonArray = object.getJSONArray(keys[keys.length - 1]
					.substring(0, keys[keys.length - 1].indexOf("[")));
			return jsonArray.get(index).toString();
		}
		return object.getString(keys[keys.length - 1]);
	}


    /**
     * 把Java对象转换为JSON数据格式
     *
     * @param object
     * @return
     */
    public static String getJson(Object object) {
        try {
            String dataJson=JSON.toJSONString(object);
            return dataJson;
        } catch (Exception e) {
            System.out.println(e);
        }
        return null;
    }

    /**
     * 把JSON数据格式转换为JAVA对象
     *
     * @param <T>
     * @param jsonData
     * @param clz
     * @return
     */
    public static <T> T readValue(String jsonData, Class<T> clz) {
        try {
            return JSON.parseObject(jsonData, clz);
        } catch (Exception e) {

			log.error("readValue 把JSON数据格式转换为JAVA对象出现异常",e);
        }
        return null;
    }
    
	public static String writeValue(Object object) {
		return JSON.toJSONString(object);
	}
}
